const Topic = require("../../models/topic");
const TopicCategory = require("../../models/topicCategory");
const { Op } = require("sequelize");

//新增一条数据
exports.addTopic = async function(topic){
    return Topic.create({
        ...topic
    })
}

//获取一条数据
exports.getTopic = async function(id){
    let topic = await Topic.findByPk(id,{
        attributes:{exclude:['createdAt','updatedAt','deletedAt']},
        include:{
            model:TopicCategory,
            attributes:['id'],
            as:'topicCategory'
        }
    });
    topic.dataValues.topicCategoryId = topic.topicCategory.id;
    return topic;
}

//更新一条数据
exports.updateTopic = async function(id,topic){
    delete topic.id;
    return Topic.update(
        {...topic},
        {where: {id: id}, individualHooks: true}
    )
}

//删除一条数据
exports.deleteTopic = async function(id){
    return Topic.destroy({
        where:{id},
        individualHooks:true
    })
}

//获取话题列表
exports.getTopicList = async function(keyword,page,size){
    page = Number(page);
    size = Number(size);
    const {rows,count} = await Topic.findAndCountAll({
        where:{
            title:{
                [Op.like]: `%${keyword}%`
            }
        },
        include:{
            model:TopicCategory,
            attributes:['id','name'],
            as:'topicCategory'
        },
        attributes:{exclude:['createdAt','updatedAt','deletedAt']},
        limit:size,
        offset:(page-1) * size,
    });
    rows.forEach(item=>{
        item.dataValues.name = item.topicCategory.name;
    });

    return {
        rows,count
    }
}